package com.gomoney.auth.service.impl;

import com.gomoney.auth.common.util.RedisUtil;
import com.gomoney.auth.mapper.SysCaptchaMapper;
import com.gomoney.auth.service.SysCaptchaService;
import com.gomoney.auth.common.util.RedisUtil;
import com.gomoney.auth.mapper.SysCaptchaMapper;
import com.gomoney.auth.service.SysCaptchaService;
import com.gomoney.oauth2.common.entity.sys.SysCaptcha;
import com.gomoney.oauth2.common.exception.RRException;
import com.gomoney.oauth2.common.util.DateUtils;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.util.Date;

@Service
@Transactional
public class SysCaptchaServiceImpl implements SysCaptchaService {

    @Autowired
    private Producer producer;

    @Autowired
    private SysCaptchaMapper sysCaptchaMapper;

    @Autowired
    private RedisUtil redisUtil;

    public String sendCode(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new RRException("uuid不能为空");
        }
        String code = producer.createText();

        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 1));
        sysCaptchaMapper.insert(captchaEntity);
        return code;
    }

    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new RRException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        sysCaptchaMapper.insert(captchaEntity);
        return producer.createImage(code);
    }

    public boolean validate(String uuid, String code) {
        SysCaptcha captchaEntity = sysCaptchaMapper.selectById(uuid);
        if (captchaEntity == null) {
            return false;
        }
        //删除验证码
        sysCaptchaMapper.deleteById(uuid);
        if (captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()) {
            return true;
        }
        return false;
    }

    @Transactional(readOnly = true)
    public SysCaptcha findSysCaptchaById(String id) {
        return sysCaptchaMapper.selectById(id);
    }
}
